package com.wise.service.cms.content.product;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wise.entities.content.Product;
import com.wise.framework.basic.DateTimeUtil;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.framework.daomodel.DaoOne4Column;
import com.wise.framework.daomodel.DaoSave;
import com.wise.framework.exception.LogicException;
import com.wise.framework.session.CurrentUserId;
import com.wise.framework.session.GetAcceptLanguage;
import com.wise.framework.validation.Precondition;
import com.wise.summer.v1.cms.content.product.AddProduct;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.List;
import java.util.Objects;

import static com.wise.model.content.ContentErrMsgs.*;
import static com.wise.service.cms.content.product.UpdateProductByIdService.setPublishTimeByStatus;

@Service
@SummerService
public class AddProductService implements SummerServiceBean<AddProduct> {

    private static final Integer LENGTH = 20;

    @Override
    public void sum(AddProduct summer) {
        if (summer.getCategoryType() == null) {
            summer.setCategoryType(0);
        }
        String lang = GetAcceptLanguage.s(true);
        //产品标题不可重复
        checkIfDuplicateTitle(summer.getTitle(), null);

        Product prod = DaoOne4Column.s(Product.class, Product._routeId, summer.getRouteId(), null);
        Precondition.checkState(Objects.isNull(prod), Err_001000250032);

        Product product = new Product();
        // 草稿
        if (summer.getDraftState() == null) {
            summer.setDraftState(false);
        }
        if (summer.getDraftState()) {
            Product draft = copyEntity(summer);
            String draftJson = JSON.toJSONString(draft);
            product.setDraft(draftJson);
            product.setName(summer.getName());
            product.setIntro(summer.getIntro());
            product.setCategoryId(summer.getCategoryId());
            product.setPageTitle(summer.getPageTitle());
            product.setLang(lang);
            product.setCategoryType(summer.getCategoryType());

            JSONArray url = summer.getUrl();
            if (url.size() > LENGTH) {
                throw new LogicException(this.getClass(), Err_001000250048);
            }
            product.setUrl(summer.getUrl().toJSONString());
            product.setCreatedBy(CurrentUserId.s(true));
            product.setCreationDate(DateTimeUtil.timestampNow());
            DaoSave.s(product);
        } else {
            BeanUtils.copyProperties(copyEntity(summer), product);
            product.setLang(lang);
            product.setDraft(null);
            product.setPublishTime(setPublishTimeByStatus(summer.getState()));
            DaoSave.s(product);
        }

        summer.setSummerResult(product);
    }

    /**
     * 检查标题是否重复
     */
    static void checkIfDuplicateTitle(String name, String id) {

        SqlSelect queryForProduct = SqlSelect.selec(Product._name + "," + Product._id)
                .fromClassName(Product.class)
                .eqLang(Product._lang)
                .eq(Product._name, name);
        List<Product> articleList = DaoList.s(Product.class, queryForProduct);
        if (!articleList.isEmpty() && !articleList.get(0).getId().equals(id)) {
            throw new LogicException(new Throwable().getStackTrace()[1].getClass(), Err_001000250051);
        }

    }

    private Product copyEntity(AddProduct summer) {

        Product temp = new Product();
        BeanUtils.copyProperties(summer, temp, Product._url);

        JSONArray url = summer.getUrl();
        JSONArray guideUrl = JSONObject.parseArray(summer.getUserGuideUrl());
        JSONArray introUrl = JSONObject.parseArray(summer.getProductIntroUrl());

        if (url.size() > LENGTH) {
            throw new LogicException(this.getClass(), Err_001000250048);
        }
        if (guideUrl.size() > LENGTH) {
            throw new LogicException(this.getClass(), Err_001000250050);
        }
        if (introUrl.size() > LENGTH) {
            throw new LogicException(this.getClass(), Err_001000250049);
        }
        temp.setUrl(summer.getUrl().toJSONString());

        temp.setCreatedBy(CurrentUserId.s(true));
        temp.setCreationDate(DateTimeUtil.timestampNow());

        return temp;
    }

}
